from twisted.protocols import basic

class MyChat(basic.LineReceiver):
    def connectionMade(self):
        self.Stat='AUTHA'
        print "Got new client!"
        self.message("""欢迎登录\r""")
        self.factory.clients.append(self)

    def connectionLost(self, reason):
        print "Lost a client!"
        self.factory.clients.remove(self)

    def lineReceived(self, line):
        s=repr(line)
        print "received+["+s+"]STAT:"+ self.Stat
        if self.Stat=='AUTHA':
            print '操作员:'
            self.message('\n\r操作员:')
            self.Stat='AUTH'
        elif self.Stat=='AUTH':
            print '请输入口令:'
            self.message('\n\r请输入口令:')
            self.Stat='PASS'
        elif self.Stat=='PASS':
            print 'MML>'
            self.message('\n\rMML>')
            self.Stat='DATA'
        elif self.Stat=='DATA':
            if s=="'quit'":
                print 'Good bye!'
                self.loseConnection()
            else:
                self.message('\n\r指令执行成功\n\rMML>')

    def message(self, message):
        self.transport.write(message)


from twisted.internet import protocol
from twisted.application import service, internet

factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []

application = service.Application("chatserver")
internet.TCPServer(2026, factory).setServiceParent(application)
